#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

void test()
{
    //C定义字符串两种形式
    //1、字符数组,C风格字符串是以'\0'结尾
    char str1[] = "hello";
    char str2[] = "world";
    str1[0] = 'H';
    printf("str1 = %s\n", str1);
    /* str1 = nullptr;//error */
    /* str1 = 0x112233455;//error */

    //2、字符指针
    cout << endl << endl;
    const char *pstr = "hello,world";
    printf("pstr = %s\n", pstr);
    pstr = "wangdao";
    printf("pstr = %s\n", pstr);

    /* cout << "1111" << endl; */
    /* pstr[0] = 'H';//error */
    /* cout << "2222" << endl; */
    printf("pstr = %s\n", pstr);
    /* cout << "3333" << endl; */

    //字符串如何获取长度
    cout << endl << endl;
    size_t len1 = sizeof(str1);
    size_t len2 = sizeof(str2);
    size_t len3 = strlen(str1);
    printf("len1 = %ld\n", len1);
    printf("len2 = %ld\n", len2);
    printf("len3 = %ld\n", len3);

    //测试指针大小的时候，不要使用sizeof，只与系统相关，与
    //指针的类型是没有关系的(重点)
    size_t len4 = sizeof(pstr);
    size_t len5 = strlen(pstr);
    printf("len4 = %ld\n", len4);
    printf("len5 = %ld\n", len5);

    int *pInt;
    size_t len6 = sizeof(pInt);
    printf("len6 = %ld\n", len6);

    //如何将str1与str2拼接到起来
    size_t len7 = len1 + len2 - 1;
    /* char str[len7];//栈 */
    char *pstr2 = static_cast<char *>(malloc(len7));
    memset(pstr2, 0, len2);
    strcpy(pstr2, str1);
    strcat(pstr2, str2);
    printf("pstr2 = %s\n", pstr2);

    free(pstr2);
    pstr2 = nullptr;
}

void test2()
{
    //C++        C
    string s1 = "hello";
    string s2 = "world";
    string s3 = s1 + s2;//不需要考虑与内存相关的操作
    cout << "s1 = " << s1 << endl
         << "s2 = " << s2 << endl
         << "s3 = " << s3 << endl;

    //将C++风格字符串转换为C风格字符串
    cout << endl << endl;
    const char *pstr = s3.c_str();
    cout << "pstr = " << pstr << endl;

    //获取C++风格字符串的长度
    cout << endl << endl;
    size_t len1 = s3.length();
    size_t len2 = s3.size();
    cout << "len1 = " << len1 << endl;
    cout << "len2 = " << len2 << endl;

    //遍历C++风格字符串
    cout << endl << endl;
    for(size_t idx = 0; idx != s3.size(); ++idx)
    {
        cout << s3[idx] << "  ";
    }
    cout << endl;

    //C++风格字符串的拼接
    cout << endl << endl;
    string s4 = s3 + "wuhan";
    cout << "s4 = " << s4 << endl;

    cout << endl;
    string s5 = s4 + 'A';
    cout << "s5 = " << s5 << endl;

    s5.append(s1);
    cout << "s5 = " << s5 << endl;
}

int main(int argc, char **argv)
{
    test2();
    return 0;
}

